package com.wbp.cms.core.user.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Preconditions;
import com.wbp.cms.client.common.domain.OrganizationDO;
import com.wbp.cms.client.common.domain.QRCodeDO;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.RoleDO;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.user.domain.UserRoleDO;
import com.wbp.cms.client.user.query.UserQuery;
import com.wbp.cms.client.user.service.UserService;
import com.wbp.cms.core.dao.OrganizationDAO;
import com.wbp.cms.core.dao.QRCodeDAO;
import com.wbp.cms.core.exception.ServiceException;
import com.wbp.cms.core.user.dao.RoleDAO;
import com.wbp.cms.core.user.dao.UserDAO;
import com.wbp.cms.core.user.dao.UserRoleDAO;

/**
 * @Description:
 * @Department:
 * @author andy.lhc
 * @date 2016年3月9日 下午2:20:41
 */
@Service("userService")
public class UserServiceImpl implements UserService {
  /**
   * 
   */
  private static final long serialVersionUID = 2554612381353266747L;

  private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

  @Resource(name = "userDAO")
  private UserDAO userDAO;

  @Resource(name = "organizationDAO")
  private OrganizationDAO organizationDAO;
  
  @Resource(name="userRoleDAO")
  private UserRoleDAO  userRoleDAO ;
  
  @Resource(name="roleDAO")
  private RoleDAO  roleDAO ;
  
  @Resource(name="qRCodeDAO")
  private QRCodeDAO  qRCodeDAO ;

  @Override
  @Transactional
  public Result<Long> addUser(UserDO userDO) {
    logger.error("addUser entry userDO:"+userDO);
    try {
      Preconditions.checkArgument(userDO != null, "参数不合法");
      Preconditions.checkArgument(userDO.getRoleId() > 0 , "roleId应>0");
      
      Long  userId = userDAO.insert(userDO) ;
      
      if(userId!=null && userId>0 && userDO.getRoleId() !=null && userDO.getRoleId() >0 ){
         UserRoleDO  userRole = new UserRoleDO();
         userRole.setUserId(userId); 
         userRole.setRoleId(userDO.getRoleId());
         
         userRoleDAO.insert(userRole) ; // insert user role relation 
      }
      
      return Result.buildSuccess(userId);
    } catch (Exception e) {
      logger.error("addUser exception,userDO:" + userDO, e);
      throw new ServiceException(BaseResultCode.DB_ERROR.getErrMsg(), e) ;
      // return Result.buildError(e.getMessage());
    }

  }

  @Override
  @Transactional
  public Result<Boolean> modifyUser(UserDO userDO) {
    logger.error("modifyUser entry userDO:"+userDO);
    try {
      Preconditions.checkArgument(userDO != null && userDO.getId() > 0 , "参数不合法,id:"+userDO.getIdCard()+",应>0");
  //     Preconditions.checkArgument(userDO.getRoleId() > 0 , "roleId应>0");
     // Preconditions.checkArgument(userDO.getOrganizationId() > 0, "organizationId应>0");
      
      int  r = userDAO.update(userDO) ;
      
      RoleDO  role = this.roleDAO.queryRoleByUserId(userDO.getId()) ; // 目前一个用户只有一种角色
      if(role !=null && userDO.getRoleId() !=null && role.getId() != userDO.getRoleId()){
            this.userRoleDAO.delete(userDO.getId()) ; // 方便处理，先删除，再增加
            
            insertRole(userDO) ;
      }else if( role == null  && userDO.getRoleId() !=null && userDO.getRoleId() > 0){
            insertRole(userDO) ;
      }
      
      if(StringUtils.isNotBlank(userDO.getMainWxUrl()) ){
        QRCodeDO  qrCodeDO =  qRCodeDAO.loadByUserId(userDO.getId() ) ;
        if(qrCodeDO == null  || StringUtils.isBlank(qrCodeDO.getMainWxUrl()) ||  !qrCodeDO.getMainWxUrl().equals(userDO.getMainWxUrl())  ){
          if(qrCodeDO != null ) {
            qRCodeDAO.delete(qrCodeDO.getId()) ;
           } 
          qrCodeDO  =new QRCodeDO();
          qrCodeDO.setUserId(userDO.getId()); 
          qrCodeDO.setMobileNumber(userDO.getMobileNumber()); 
          qrCodeDO.setMainWxUrl(userDO.getMainWxUrl());
          qrCodeDO.setUserName(userDO.getUserName());
          
          qRCodeDAO.insert(qrCodeDO) ; 
        } 
      }
      
      return Result.buildSuccess( r > 0);
    } catch (Exception e) {
      logger.error("modifyUser exception,userDO:" + userDO, e);
      throw new ServiceException(BaseResultCode.DB_ERROR.getErrMsg(), e) ;
      // return Result.buildError(e.getMessage());
    }
  }
  
  private void  insertRole(UserDO userDO){
    UserRoleDO  userRole = new UserRoleDO();
    userRole.setUserId(userDO.getId()); 
    userRole.setRoleId(userDO.getRoleId());
    this.userRoleDAO.insert(userRole) ;
  }
  
  @Override
  public Result<UserDO> queryUserByUserName(String userName){
    Preconditions.checkArgument(StringUtils.isNotEmpty(userName), "userName不能为空");
    UserQuery  userQuery = new UserQuery(); 
    userQuery.setUserName(userName); 
    List<UserDO> list = this.userDAO.query(userQuery) ;
    if(list !=null && !list.isEmpty() )
        return Result.buildSuccess(list.get(0) );
    return Result.buildSuccess(null) ;
  }

  @Override
  public Result<UserDO> queryUserById(Long userId) {
    logger.error("modifyUser entry userId:"+userId );
    try {
      // 参数的校验放在controller层去做,service层只做必要的参数验证
      Preconditions.checkNotNull(userId, "userId:"+userId+",不能为空");

      UserDO  user  = userDAO.load(userId) ;
      if(user.getOrganizationId() !=null && user.getOrganizationId() > 0){
        OrganizationDO org = this.organizationDAO.load(user.getOrganizationId()) ;
        if(org !=null){
           user.setOrganizationDO(org);
           user.setOrganizationName(org.getName()); 
        }
      }
      
      RoleDO  role = this.roleDAO.queryRoleByUserId(user.getId()) ;
      if(role !=null){
        user.setRoleDO(role);
        user.setRoleId(role.getId());
      }
      
      QRCodeDO  qRCodeDO = this.qRCodeDAO.loadByUserId(user.getId()) ;
      if(qRCodeDO !=null){
        user.setMainWxUrl(qRCodeDO.getMainWxUrl()); 
      }
      
      return Result.buildSuccess(user);
    } catch (Exception e) {
      logger.error("queryUserById exception,userId:" + userId, e);
      throw new ServiceException(BaseResultCode.DB_ERROR.getErrMsg(), e) ;
      // return Result.buildError(e.getMessage());
    }
  }

  @Override
  public Result<Boolean> addOrganization2User(Long userId, Long organizationId) {
    logger.error("modifyUser entry userId:"+userId+",organizationId:"+organizationId );
    try {
      Preconditions.checkNotNull(userId, "userId不能为空");
      Preconditions.checkNotNull(organizationId, "organizationId不能为空");

      UserDO user = userDAO.load(userId);
      Preconditions.checkNotNull(user, "userId:" + userId + ",找不到对应的User");
      Preconditions.checkNotNull(organizationDAO.load(organizationId), "organizationId:"
          + organizationId + ",找不到对应的组织机构");

      Boolean flag = true;
      if (user.getOrganizationId() != null && user.getOrganizationId() == organizationId) {
        return Result.buildSuccess(flag); // 相同则不更新
      }

      user.setOrganizationId(organizationId);
      flag = userDAO.update(user) == 1;

      return Result.buildSuccess(flag);
    } catch (Exception e) {
      logger.error("queryUsers exception,userId:" + userId + ",organizationId:" + organizationId, e);
      throw new ServiceException(BaseResultCode.DB_ERROR.getErrMsg(), e) ;
      // return Result.buildError(e.getMessage());
    }
  }

  @Override
  public Result<List<UserDO>> queryUsers(UserQuery userQuery) {
    logger.error("modifyUser entry userQuery:"+userQuery );
    Preconditions.checkNotNull(userQuery, "userQuery不能为空");
    int count = 0;
    List<UserDO> userList = null;
    
    try {
      if (userQuery.getOrganizationId()== null || userQuery.getOrganizationId() <= 0) {
          count = userDAO.queryCount(userQuery) ;
          if (count > 0)
               userList = userDAO.query(userQuery);
       } else {
           count = userDAO.queryUserByOrgCount(userQuery) ;
           if (count > 0)
              userList = userDAO.queryUserByOrg(userQuery) ;
       }
      
      if(count > 0){   // 查组织机构
        for(UserDO user: userList){
            if(user.getOrganizationId() !=null && user.getOrganizationId()>0){
                  OrganizationDO org = organizationDAO.load(user.getOrganizationId());
                  user.setOrganizationName( (org ==null ? "" : org.getName()) );
            }else
              user.setOrganizationName("");
            
            RoleDO role = this.roleDAO.queryRoleByUserId(user.getId()) ;  // 查角色
            if(role!=null){
                user.setRoleDO(role);
                user.setRoleId(role.getId());
            }
         }
      } 
      
      return Result.buildSuccess(count, userList);
    } catch (Exception e) {
      logger.error("queryUsers exception,userQuery:" + userQuery, e);
      return Result.buildError(e.getMessage());
    }

  }

  @Override
  public Result<UserDO> login(String userName, String password) {
    logger.error("modifyUser entry userName:"+userName+",password:"+password);
    
    if(StringUtils.isEmpty(userName))
      return Result.buildError(BaseResultCode.INVALID_PARAMETER) ;
    if(StringUtils.isEmpty(password))
      return Result.buildError(BaseResultCode.INVALID_PARAMETER) ;
    UserDO  user = userDAO.queryUserByUserName(userName) ; 
    if(user == null )
      return  Result.buildError(BaseResultCode.USER_USERNAME_ERROR) ;
    String  dbPwd = user.getPwd() ;
    if(!password.equals(dbPwd))
        return  Result.buildError(BaseResultCode.USER_PASSOWRD_ERROR) ;
    
    if(user.getOrganizationId() !=null && user.getOrganizationId() > 0 ){
      OrganizationDO   organization = organizationDAO.load(user.getOrganizationId()) ;
      if(organization !=null ){
         user.setOrganizationDO(organization);
         user.setOrganizationId(organization.getId());
          user.setOrganizationName(organization.getName());
      }
            
    }
    
     RoleDO role = this.roleDAO.queryRoleByUserId(user.getId()) ;
     if(role!=null){
         user.setRoleDO(role);
         user.setRoleId(role.getId());
     }
    return Result.buildSuccess(user);
  }

  
  @Override
  public Result<List<UserDO>> queryUsersByOrgId(Long orgId) {
    if(orgId == null || orgId <=0)
      return Result.buildError(BaseResultCode.INVALID_PARAMETER) ;
    UserQuery userQuery =new UserQuery();
    userQuery.setOrganizationId(orgId);
    int count = this.userDAO.queryCount(userQuery) ;
    List<UserDO> ul  = null ;
    if(count > 0 ){
       ul  = this.userDAO.query(userQuery) ;
       for(UserDO u : ul){
         if(u.getOrganizationId() !=null && u.getOrganizationId() >0){
              OrganizationDO  orgDO = this.organizationDAO.load(u.getOrganizationId()) ;
              u.setOrganizationDO(orgDO);
              u.setOrganizationId(orgDO.getId() ) ;
              u.setOrganizationName(orgDO.getName());
         } 
              
       }
    }
    return Result.buildSuccess(count, ul) ;
  }


}
